package com.weishuang.monitor.leader.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.weishuang.monitor.leader.commons.entity.BaseEntity;
import com.weishuang.monitor.leader.commons.enums.SCODE;
import com.weishuang.monitor.leader.commons.utils.UserUtils;
import com.weishuang.monitor.leader.entity.SysUser;
import com.weishuang.monitor.leader.entity.dto.UserDTO;
import com.weishuang.monitor.leader.mapper.SysUserMapper;
import com.weishuang.monitor.leader.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author weishuang
 * @since 2021-03-23
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    /**
     * 根据用户名获取用户信息（登录）
     * @param username
     * @return
     */
    @Override
    public SysUser getUserByUsername(String username) {
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserLambdaQueryWrapper.eq(SysUser::getUsername, username);
        sysUserLambdaQueryWrapper.eq(SysUser::getStatus, SCODE.STATUS_NORMAL.getValue());
        SysUser sysUser = baseMapper.selectOne(sysUserLambdaQueryWrapper);
        return sysUser;
    }

    /**
     * 分页查询用户列表
     * @param user
     * @return
     */
    @Override
    public Page<SysUser> getUserPage(UserDTO user) {
        String userId = UserUtils.getUserId();
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(user.getUsername())) {
            queryWrapper.like(SysUser::getUsername, user.getUsername());
        }
        if (StringUtils.isNotBlank(user.getRealName())) {
            queryWrapper.like(SysUser::getRealName, user.getRealName());
        }
        if (user.getPhone() != null) {
            queryWrapper.like(SysUser::getPhone, user.getPhone());
        }
        queryWrapper.eq(BaseEntity::getStatus, SCODE.STATUS_NORMAL.getValue());
        queryWrapper.ne(SysUser::getId, userId);
        queryWrapper.orderByDesc(BaseEntity::getCreatedTime);
        user.startPage();
        Page<SysUser> sysUsers = (Page<SysUser>) baseMapper.selectList(queryWrapper);
        return sysUsers;
    }
}
